<template>
	<div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<!-- <div class="search-s page-public-s" style="box-sizing: border-box;"> -->
			<!-- <el-card shadow="never" :body-style="{ paddingBottom: '0' }">
                    <el-form class="box-f" :model="queryRiskForm" ref="queryForm" :inline="true">
                        <el-form-item label="风险等级：">
                            <el-select v-model="queryRiskForm.riskType" class="m-2" placeholder="请选择风险等级">
                                <el-option v-for="item in optionsRisk" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="流程状态：">
                            <el-select v-model="queryRiskForm.flowState" class="m-2" placeholder="请选择流程状态">
                                <el-option v-for="item in optionsFlow" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            
                        </el-form-item>
                    </el-form>
                </el-card> -->
			<!-- </div> -->

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table :data="list" class="w-h-100" style="width: 100%" border v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" />

										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="v_ApplyEmpName" label="申请人" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="d_ApplyTime" label="申请时间" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="流程状态" align="center">
											<el-table-column min-width="120" label="风险等级" align="center">
												<template #header>
													<SearchModel typeId="v_FlowinstanceState" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.v_FlowinstanceState }}
												</template>
											</el-table-column>
										</el-table-column>

										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="v_AnalysisUnitName" label="作业活动/场所" align="center" />

										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="v_HazardousFactors" label="危险因素" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="v_Event" label="可能导致的事故类型" align="center" />

										<el-table-column min-width="120" :show-overflow-tooltip="true" label="风险评价" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" prop="v_RiskAssessmentL" label="风险评价L" align="center" />
											<el-table-column min-width="120" :show-overflow-tooltip="true" prop="v_RiskAssessmentE" label="风险评价E" align="center" />
											<el-table-column min-width="120" :show-overflow-tooltip="true" prop="v_RiskAssessmentC" label="风险评价C" align="center" />
											<el-table-column min-width="120" :show-overflow-tooltip="true" prop="v_RiskAssessmentD" label="风险评价D" align="center" />
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="风险等级" align="center">
											<el-table-column min-width="120" label="风险等级" align="center">
												<template #header>
													<SearchModel typeId="v_RiskLevelName" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.v_RiskLevelName }}
												</template>
											</el-table-column>
										</el-table-column>

										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="v_ControlMeasure" label="风险控制措施" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="v_IdentificationPersonnel" label="辨识人员" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="isOverdue" label="超期未复评" align="center">
											<template #default="scope">
												{{ scope.row.isOverdue ? '是' : '否' }}
											</template>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="d_ReEvaluationDate" label="重新复评时间" align="center" />

										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdUserName" label="创建人" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdTime" label="创建时间" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="updatedUserName" label="更新人" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="updatedTime" label="更新时间" align="center" />
										<el-table-column min-width="180" label="操作" align="center" fixed="right">
											<el-table-column min-width="180" align="center" fixed="right">
												<template #header>
													<el-button @click="searchClick" icon="ele-Search" type="primary" text> 查询 </el-button>
													<el-button @click="resetClick" icon="ele-Refresh" class="clear-bg" text> 重置 </el-button>
												</template>
												<template #default="scope">
													<div class="operate-s">
														<template v-if="$hasPer('ChangeRiskIdentification1:create')">
															<el-button v-if="scope.row.n_FlowinstanceState == 0" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary"> 创建申请 </el-button>
														</template>

														<template v-if="$hasPer('ChangeRiskIdentification2:chehui')">
															<el-button v-if="scope.row.n_FlowinstanceState == 1" @click="revocationClick(scope.row, getData)" class="icon-e" icon="ele-Close" size="small" text type="success">
																撤回
															</el-button>
														</template>

														<template v-if="$hasPer('ChangeRiskIdentification3:chongxin')">
															<el-button v-if="scope.row.n_FlowinstanceState == 3" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary">
																重新创建申请
															</el-button>
														</template>

														<template v-if="$hasPer('ChangeRiskIdentification4:edit')">
															<el-button
																v-if="scope.row.n_FlowinstanceState == 0 || scope.row.n_FlowinstanceState == 3"
																@click="editClick(scope.row)"
																class="icon-e"
																icon="ele-Edit"
																size="small"
																text
																type="primary"
															>
																编辑
															</el-button>
														</template>

														<template v-if="$hasPer('ChangeRiskIdentification5:delete')">
															<el-button
																v-if="scope.row.n_FlowinstanceState == 0 || scope.row.n_FlowinstanceState == 3"
																@click="deleteHandle(scope.row.id, getData)"
																class="icon-e"
																icon="ele-Delete"
																size="small"
																text
																type="danger"
															>
																删除
															</el-button>
														</template>

														<div v-if="scope.row.n_FlowinstanceState === 2">-</div>
													</div>
												</template>
											</el-table-column>
										</el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<!-- 新增and编辑 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVisible" title="工作审批申请" width="50%" @close="cancelRiskUseClick">
			<el-form label-width="120px" ref="ruleFormRef" :model="ruleForm" size="default" :rules="rules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="l_AnalysisUnitId" label="作业活动场所" disabled>
							<el-select v-model="ruleForm.l_AnalysisUnitId" class="m-2" placeholder="请选择作业活动场所" style="width: 100%">
								<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="v_HazardousFactors" label="危害因素">
							<el-input v-model="ruleForm.v_HazardousFactors" placeholder="岗位风险因素" clearable />
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="v_Event" label="可能导致事故">
							<el-input v-model="ruleForm.v_Event" placeholder="可能导致事故" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="风险评价L">
							<el-input v-model="ruleForm.v_RiskAssessmentL" placeholder="风险评价L" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="风险评价E">
							<el-input v-model="ruleForm.v_RiskAssessmentE" placeholder="风险评价E" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="风险评价C">
							<el-input v-model="ruleForm.v_RiskAssessmentC" placeholder="风险评价C" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="风险评价D">
							<el-input v-model="ruleForm.v_RiskAssessmentD" placeholder="风险评价D" clearable />
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="n_RiskLevel" label="危害因素">
							<el-select v-model="ruleForm.n_RiskLevel" class="m-2" placeholder="请选择作业活动场所" style="width: 100%">
								<el-option v-for="item in optionsRisk" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="v_ControlMeasure" label="风险控制措施">
							<el-input v-model="ruleForm.v_ControlMeasure" placeholder="风险控制措施" clearable />
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="v_IdentificationPersonnel" label="辨识人员">
							<el-input v-model="ruleForm.v_IdentificationPersonnel" placeholder="辨识人员" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="重新复评时间">
							<el-date-picker style="width: 100%" v-model="ruleForm.d_ReEvaluationDate" format="YYYY/MM/DD" value-format="YYYY/MM/DD" type="date" placeholder="重新复评时间" />
						</el-form-item>
					</el-col>

					<template v-if="isWorkFlow">
						<el-divider content-position="left"> 工作流审批信息 </el-divider>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<commonProcessTemplate v-if="showDialogVisible" :tempId="typeCode" @modelIdInfo="modelIdInfo" @ueseIdInfo="ueseIdInfo" />
						</el-col>
					</template>
				</el-row>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelRiskUseClick">取消</el-button>
					<el-button type="primary" @click="controlRiskUseClick(getData)">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted } from 'vue';
import getTableData from '/@/utils/getTableData';
import {
	deleteRiskIdentifyListApi,
	updateRiskIdentifyListApi,
	getRiskIdentifyListApi,
	getWorkPlaceApi,
	createRiskWorkFlowApi,
	revocationRiskWorkFlowApi,
} from '/@/api/sms/HazardousChemicalsInterface';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import commonProcessTemplate from '/@/components/workFlow/commonProcessTemplate.vue';
import SearchModel from '/@/views/sms/component/search-model.vue';
export default defineComponent({
	name: 'friend-merchant-manage',
	components: {
		SearchModel,
		commonProcessTemplate,
	},
	setup() {
		/***** 变量 *****/
		const transferVal = ref(); // 需要查询的值
		const transferVal1 = ref(); // 需要查询的值
		const showDialogVisible = ref(false);
		let searchObj: any = reactive({});
		const optionsRisk = [
			{ label: '低风险', value: 0 },
			{ label: '一般风险', value: 1 },
			{ label: '较大风险', value: 2 },
			{ label: '重大风险', value: 3 },
		];
		const optionsFlow = [
			{ label: '待提交', value: 0 },
			{ label: '审核中', value: 1 },
			{ label: '审核通过', value: 2 },
			{ label: '撤回', value: 3 },
			{ label: '驳回', value: 4 },
		];
		let queryRiskForm = reactive({
			riskType: '',
			flowState: '',
		});

		const ruleForm = reactive({
			l_AnalysisUnitId: null, //作业活动场所
			v_HazardousFactors: '', //危害因素
			v_Event: '', //危害因素
			v_RiskAssessmentL: '', //危害因素
			v_RiskAssessmentE: '', //风险评价L
			v_RiskAssessmentC: '', //风险评价E
			v_RiskAssessmentD: '', //风险评价D
			n_RiskLevel: 0, //风险等级
			v_ControlMeasure: '', //危害因素
			v_IdentificationPersonnel: '', //辨识人员
			d_ReEvaluationDate: '', //重新复评时间
			l_SourceId: '', //来源ID
		});
		/***** searchClick 查询按钮 *****/
		const searchClick = () => {
			// searchObj.N_RiskLevel = queryRiskForm.riskType;
			// searchObj.N_FlowinstanceState = queryRiskForm.flowState;
			let newObj = Object.keys(searInfo.value);
			if (newObj.length !== 0) {
				newObj.map((i: any) => {
					searchObj[i] = searInfo.value[i];
				});
			}
		};

		/***** resetClick 重置按钮 *****/
		const resetClick = () => {
			// queryRiskForm.riskType = '';
			// queryRiskForm.flowState = '';
			searInfo.value = {};
			let newObj = Object.keys(searchObj);
			if (newObj.length !== 0) {
				newObj.map((i: any) => {
					searchObj[i] = '';
					// console.log(i);
				});
			}
			initInfoFun();
		};

		/***** addNodeClick 新增 *****/
		const addNodeClick = async () => {
			showDialogVisible.value = true;
		};

		/***** nodeClick 编辑 *****/
		const saveId = ref();
		const isWorkFlow = ref(true);
		const nodeClick = async (row: any) => {
			console.log(row);
			ruleForm.l_AnalysisUnitId = row.l_AnalysisUnitId; //作业活动场所
			ruleForm.v_HazardousFactors = row.v_HazardousFactors; //危害因素
			ruleForm.v_Event = row.v_Event; //危害因素
			ruleForm.v_RiskAssessmentL = row.v_RiskAssessmentL; //危害因素
			ruleForm.v_RiskAssessmentE = row.v_RiskAssessmentE; //风险评价L
			ruleForm.v_RiskAssessmentC = row.v_RiskAssessmentC; //风险评价E
			ruleForm.v_RiskAssessmentD = row.v_RiskAssessmentD; //风险评价D
			ruleForm.n_RiskLevel = row.n_RiskLevel; //风险等级
			ruleForm.v_ControlMeasure = row.v_ControlMeasure; //危害因素
			ruleForm.v_IdentificationPersonnel = row.v_IdentificationPersonnel; //辨识人员
			ruleForm.d_ReEvaluationDate = row.d_ReEvaluationDate; //重新复评时间
			ruleForm.l_SourceId = row.l_SourceId;

			saveId.value = row.id;

			showDialogVisible.value = true;
		};

		/*** deleteHandle 删除数据事件 */
		const deleteHandle = async (val: String | Number, updateFun: Function) => {
			ElMessageBox.confirm('请确定删除此条数据', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(async () => {
					let param = { id: val };
					try {
						let res: any = await deleteRiskIdentifyListApi(param);
						if (res.success) {
							updateFun();
						}
					} catch (err) {
						return;
					}
				})
				.catch(() => {
					ElMessage({
						type: 'info',
						message: '删除失败',
					});
				});
		};

		let res1: any, res2: any;
		const ueseIdInfo = (val: any) => {
			console.log(val.value);
			res1 = val.value;
		};
		const modelIdInfo = (val: any) => {
			res2 = val;
		};
		const controlRiskUseClick = async (updataFun: Function) => {
			let prams = {
				id: saveId.value,
				schemeId: res2,
				nextNodeDesignates: res1,
			};
			await createRiskWorkFlowApi(prams);
			console.log(prams);
			await cancelRiskUseClick();
			await updataFun();
		};

		const cancelRiskUseClick = () => {
			res1 = null;
			res2 = null;
			showDialogVisible.value = false;
			isWorkFlow.value = true;
		};

		const revocationClick = (row: any, updateFun: Function) => {
			ElMessageBox.confirm('请确定撤回此条数据', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(async () => {
					let param = { id: row.id };
					try {
						let res: any = await revocationRiskWorkFlowApi(param);
						if (res.success) {
							updateFun();
						}
					} catch (err) {
						return;
					}
				})
				.catch(() => {
					ElMessage({
						type: 'info',
						message: '撤回失败',
					});
				});
		};

		const editClick = (row: any) => {
			isWorkFlow.value = false;
			nodeClick(row);
		};

		const cancelDetailClick = () => {
			showDialogVisible.value = false;
		};

		/*** cancelUseClick  弹窗取消事件 */
		const cancelUseClick = () => {
			showDialogVisible.value = false;
			saveId.value = '';
			ruleForm.l_AnalysisUnitId = null; //作业活动场所
			ruleForm.v_HazardousFactors = ''; //危害因素
			ruleForm.v_Event = ''; //危害因素
			ruleForm.v_RiskAssessmentL = ''; //危害因素
			ruleForm.v_RiskAssessmentE = ''; //风险评价L
			ruleForm.v_RiskAssessmentC = ''; //风险评价E
			ruleForm.v_RiskAssessmentD = ''; //风险评价D
			ruleForm.n_RiskLevel = 0; //风险等级
			ruleForm.v_ControlMeasure = ''; //危害因素
			ruleForm.v_IdentificationPersonnel = ''; //辨识人员
			ruleForm.d_ReEvaluationDate = ''; //重新复评时间
			ruleForm.l_SourceId = '';
			isWorkFlow.value = true;
		};

		/*** controlUseClick  弹窗提交事件 */
		const controlUseClick = async (formEl: FormInstance | undefined, updateFun: Function) => {
			if (!formEl) return;
			await formEl.validate((valid, fields) => {
				if (valid) {
					if (saveId.value) {
						updateRiskIdentifyListApi({ ...ruleForm, id: saveId.value }).then((res) => {
							console.log(res);
							cancelUseClick();
							updateFun();
						});
					}
				} else {
					console.log('error submit!', fields);
				}
			});
		};

		/*** ruleFormRef  表单校验 */

		const ruleFormRef = ref();
		const rules = reactive({
			l_AnalysisUnitId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			v_HazardousFactors: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			v_Event: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			n_RiskLevel: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			v_ControlMeasure: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			v_IdentificationPersonnel: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			d_ReEvaluationDate: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
		});

		/*** 初始化数据 */
		const basicsInfo: any = ref([]);
		const initInfoFun = () => {
			basicsInfo.value = [
				{
					typeId: 'v_FlowinstanceState', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
					typeNam: '', // 输入类型(number,text等) --- 选填
					searchVal: 'N_FlowinstanceState', // 查询字段 --- 必填
					defaultVal: '', // 字段默认值 --- 选填
					placeholder: '流程状态', // placeholder数据
					defaultProp: optionsFlow, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
					eventType: '', // 事件类型（如burl/change等） --- 选填
					defaultEvent: '', // 事件名称 --- 选填
				},
				{
					typeId: 'v_RiskLevelName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
					typeNam: '', // 输入类型(number,text等) --- 选填
					searchVal: 'N_RiskLevel', // 查询字段 --- 必填
					defaultVal: '', // 字段默认值 --- 选填
					placeholder: '风险等级', // placeholder数据
					defaultProp: optionsRisk, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
					eventType: '', // 事件类型（如burl/change等） --- 选填
					defaultEvent: '', // 事件名称 --- 选填
				},
			];
		};

		const searInfo: any = ref();
		const searchHandel = (val: any) => {
			searInfo.value = val;
		};

		// 获取岗位
		const options1: any = ref([]);

		onMounted(async () => {
			const res = await getWorkPlaceApi();
			console.log(res);
			res.data.forEach((element: any) => {
				options1.value.push({
					label: element.v_RiskPartitionName,
					value: element.id,
				});
			});

			await initInfoFun();
		});

		const typeCode = 'SmsDCRiskIdentificationChangeApply';

		return {
			...getTableData(getRiskIdentifyListApi, {}, searchObj),
			searchClick,
			transferVal,
			transferVal1,
			showDialogVisible,
			deleteHandle,
			ruleForm,
			nodeClick,
			saveId,
			cancelUseClick,
			controlUseClick,
			rules,
			ruleFormRef,
			addNodeClick,
			cancelDetailClick,
			options1,
			resetClick,
			optionsRisk,
			queryRiskForm,
			optionsFlow,
			typeCode,
			ueseIdInfo,
			modelIdInfo,
			controlRiskUseClick,
			cancelRiskUseClick,
			revocationClick,
			editClick,
			isWorkFlow,
			basicsInfo,
			searchHandel,
		};
	},
});
</script>

<style lang="scss">
@import '../style/public.scss';
</style>

<style scoped lang="scss">
#friend-merchant-manage {
	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}

	:deep(.el-card__body) {
		height: 100%;
	}

	:deep(.el-card) {
		border: none !important;
	}

	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}

	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}

	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}
}
</style>
